import axios from 'axios'
import { message } from 'ant-design-vue'

//设置请求头
function getCookie(name) {
  const cookies = document.cookie.split(';')
  for (let cookie of cookies) {
    const [key, value] = cookie.trim().split('=')
    if (key === name) {
      return decodeURIComponent(value)
    }
  }
  return null // 未找到
}

const env = import.meta.env.VITE_APP_ENV
let allCookies
if (env === 'dev') {
  allCookies =
    'Online.3c9e656d1f13e0fc2cbc3af658e20243.a2ea35f3dbdc77be94b2a95c4f0464ad.eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJYTUdleUoxYzJWeVRtRnRaU0k2SW5sMWJuZGxhU0lzSW1sa0lqb2lNelFpTENKeVpXZHBiMjVKWkNJNklqQWlMQ0pwY0VGa1pISmxjM01pT2lJeE56SXVNVFl1TWpVMExqSXlJbjA9R0lDViIsImp0aSI6IjM5MzE3MiIsImlhdCI6MTc1MzkyNDA2N30.q46CDRGEWL8-Xc_iQGd1am8xHEa-a9FQhWU45WIbLGslEj93I4yU6ASgWEz7O7iZhu-ZzGYRHQH-pIv65LBFyg; Path=/; SameSite=Lax;'
} else if (env === 'pro') {
  allCookies = getCookie('X-Subject-Token')
}

//参数处理
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== '' &&
            typeof value[key] !== 'undefined'
          ) {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_URL,
})
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    if (allCookies) {
      config.headers.Authorization = `Bearer ${allCookies}`
      // config.headers.Cookie = `${allCookies}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use((res) => {
  if (res.data.code === 401) {
    location.href = '/login'
  }
  return res
})
export default request
